"""
FileName：api_client.py
Description：
Author：gaojiahui
Time：2025/8/18 20:09
Website：https://gitee.com/gao-jiahui
"""
import logging
from typing import Optional, Dict, Any

import requests

from config.settings import settings

from core.exceptions import APIrequestError
from utils.allure_util import attach_request_details


class APIClient:
    def __init__(self):
        self.session = requests.Session()
        self.base_url = settings.BASE_URL
        self.timeout = settings.API_TIMEOUT
        from core.logger import logger  # 复用已配置的 "PIG_API_TEST" logger
        self.logger = logger.getChild("API_Client")

    def _send_request(self, method, path, **kwargs):
        """发送HTTP请求"""
        url = f"{self.base_url}{path}"
        skip_auth = kwargs.pop('skip_auth', False)

        # 添加认证头（除非明确跳过）
        if not skip_auth and not path.startswith("/auth"):
            from core.auth_manager import auth_manager
            token = auth_manager.get_token()
            headers = kwargs.get('headers', {})
            headers.setdefault('Authorization', f'Bearer {token}')
            kwargs['headers'] = headers

        # 记录请求
        self.logger.info(f"请求: {method} {url}")

        try:
            response = self.session.request(
                method,
                url,
                timeout=self.timeout,
                **kwargs
            )

            # 记录响应
            self.logger.info(f"响应状态: {response.status_code}")
            self.logger.debug(f"响应内容: {response.text[:500]}")

            # 附加到Allure报告
            attach_request_details(method, url, kwargs, response)

            return response
        except requests.exceptions.RequestException as e:
            self.logger.error(f"请求异常: {str(e)}")
            raise APIrequestError(f"API请求失败: {str(e)}")

    def get(self, path:str, params: Optional[Dict] = None, **kwargs):
        return self._send_request('GET', path, params=params, **kwargs)

    def post(self, path: str, data: Optional[Dict] = None, json: Optional[Any] = None, **kwargs):
        return self._send_request('POST', path, data=data, json=json, **kwargs)

    def put(self, path: str, json: Optional[Dict] = None, **kwargs):
        return self._send_request('PUT', path, json=json, **kwargs)

    def delete(self, path: str, **kwargs):
        return self._send_request('DELETE', path, **kwargs)

# 全局API客户端实例
api_client = APIClient()